package com.dahua.ui.main;

import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dahua.R;
import com.dahua.bean.ScanResult;
import com.dahua.utils.AppApplication;
import com.dahua.utils.UserPreference;
import com.zbar.CameraPreview;

import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;


/**
 * Initial the camera
 *
 * @author lzh
 */
public class MipcaActivityCaptureZbar extends Activity {

    private Camera mCamera;
    private CameraPreview mPreview;
    private Handler autoFocusHandler;
    private FrameLayout preview;

    ImageScanner scanner;

    private boolean previewing = true;

    static {
        System.loadLibrary("iconv");
    }

    TextView tvGo;
    TextView text_scan_title;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_capture_zbar);

        text_scan_title = (TextView) findViewById(R.id.text_scan_title);
        tvGo = (TextView) findViewById(R.id.tv_go);
        tvGo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MipcaActivityCaptureZbar.this, ScanPrepareUploadAct.class));
                finish();
            }
        });


        autoFocusHandler = new Handler();
        mCamera = getCameraInstance();

        /* Instance barcode scanner */
        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);

        mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
        preview = (FrameLayout) findViewById(R.id.cameraPreview);
        preview.addView(mPreview);


        AppApplication.aliveActivitys.add(this);
        setScreenBrightness(255);

        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int option = View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            window.getDecorView().setSystemUiVisibility(option);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.title_background));
        }
    }

    private void setScreenBrightness(int paramInt) {
        Window localWindow = getWindow();
        WindowManager.LayoutParams localLayoutParams = localWindow.getAttributes();
        float f = paramInt / 255.0F;
        localLayoutParams.screenBrightness = f;
        localWindow.setAttributes(localLayoutParams);
    }


    public void back(View view) {
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mCamera == null) {
            mCamera = getCameraInstance();
            mPreview.setmCamera(mCamera);
            mCamera.setPreviewCallback(previewCb);
            mCamera.startPreview();
            previewing = true;
            mCamera.autoFocus(autoFocusCB);
        }
        preview.removeAllViews();
        preview.addView(mPreview);


        String lang = UserPreference.getInstance(this).getLang();
        readAssetsFile(lang);
    }

    private Properties properties;

    private void readAssetsFile(String lang) {
        properties = new Properties();
        try {
            InputStream is = getAssets().open("part2/resources/js/lang/lang_" + lang + ".properties");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
            properties.load(bufferedReader);
        } catch (Exception e) {
            e.printStackTrace();
        }
        tvGo.setText(properties.getProperty("partner_Continue"));
        text_scan_title.setText(properties.getProperty("User_Center_Scan2"));
    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseCamera();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
        releaseCamera();
    }


    /**
     * A safe way to get an instance of the Camera object.
     */
    public Camera getCameraInstance() {
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return c;
    }

    private void releaseCamera() {
        if (mCamera != null) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    private Runnable doAutoFocus = new Runnable() {
        public void run() {
            if (previewing)
                mCamera.autoFocus(autoFocusCB);
        }
    };

    Camera.PreviewCallback previewCb = new Camera.PreviewCallback() {
        public void onPreviewFrame(byte[] data, Camera camera) {
            Camera.Parameters parameters = camera.getParameters();
            Camera.Size size = parameters.getPreviewSize();

            Image barcode = new Image(size.width, size.height, "Y800");
            barcode.setData(data);

            int result = scanner.scanImage(barcode);

            if (result != 0) {

                SymbolSet syms = scanner.getResults();
                for (Symbol sym : syms) {

                    dealScanResult(sym.getData());

                    break;
                }
            }
        }
    };

    // Mimic continuous auto-focusing
    Camera.AutoFocusCallback autoFocusCB = new Camera.AutoFocusCallback() {
        public void onAutoFocus(boolean success, Camera camera) {
            autoFocusHandler.postDelayed(doAutoFocus, 1000);
        }
    };

    String preStr;


    private void dealScanResult(String resultString) {
        if (resultString.equals("")) {
            Toast.makeText(this, properties.getProperty("Scan_failed"), Toast.LENGTH_SHORT).show();
        } else if (resultString.contains(".") || resultString.contains("#")) {
            if (!resultString.equals(preStr)) {
                preStr = resultString;
                Toast.makeText(this, properties.getProperty("Scan_format_failed"), Toast.LENGTH_SHORT).show();
            }

        } else {
            releaseCamera();
            Intent resultIntent = new Intent(getApplicationContext(), ScanPrepareUploadAct.class);
            Bundle bundle = new Bundle();
            bundle.putString("result", resultString);
//			bundle.putParcelable("bitmap", barcode);
            resultIntent.putExtras(bundle);
//			this.setResult(RESULT_OK, resultIntent);
            ScanResult bean = new ScanResult();
            bean.setContent(resultString);
            bean.setTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
//            list.add(bean);
            String curr = UserPreference.getInstance(getApplicationContext()).getData();
            if ("".equals(curr)) {
                UserPreference.getInstance(getApplicationContext()).setData(bean.getContent() + "@@" + bean.getTime());
            } else {
                UserPreference.getInstance(getApplicationContext()).setData(curr + "##" + bean.getContent() + "@@" + bean.getTime());
            }
//            resultIntent.putExtra("list", (Serializable) list);
            startActivity(resultIntent);
            finish();
        }
    }


}